setting.callback.onClick = getUser;
$(document).ready(function(){
	/**
	 * 获取列表页面（行为）按钮
	 */
	var authCondition = {
			//userId:$("#index #userId").val(),
			menuCode:curMenu.code,
			drawerCode:行为类型_前端组件,
			authAreaCode:授权分类_用户管理_列表,
			callback:action,
			con:"#listform"}
	findResourcesByUserId(authCondition);
});

/**
 * 获取部门数据
 * @param data
 */
function getUser(event,treeId,treeNode){
	search(page_);
}

/**
 * 定义分页全局变量
 */
var page_ = new page({search:search,callback:func});

/**
 * 定义容器全局变量
 */
var con = new container({
	datagrid:'#datagrid',
	datagridtoolbar:'#datagrid-toolbar', 
	singleSelect:true});

/**
 * 查询
 * @param page
 */
function search(pg){
	if(pg == undefined){
		pg = page_;
	}
	var url = ctx + "/user/query";
	page_.pageSize = pg.pageSize;
	page_.pageNumber = pg.pageNumber;
	query(url, getCondition(), con, page_);
}

/**
 * 获取查询条件
 * @returns {condition}
 */
function getCondition(){
	
	var organTree = $.fn.zTree.getZTreeObj("organTree");
	var organ = organTree.getSelectedNodes();
	
	var condition = {};
	
	condition.organId = organ[0].id;
	
	/*condition.departName = $("#listform #dname").textbox('getValue');*/
	condition.username = $("#listform #uname").textbox('getValue');
	
	return condition;
}

/**
 * 回调函数
 */
function func(){
	$("#datagrid").datagrid({onClickRow:function(index,row){
	}});
}

/**
 * 添加
 */
function add(){
	
	var organTree = $.fn.zTree.getZTreeObj("organTree");
	var organ = organTree.getSelectedNodes();
	
	if(organ.length == 0){
		message("请选择机构");
		return;
	}

	$('#dialog').dialog({
	    title: '添加',
	    width: 600,
	    height: 500,
	    closed: false,
	    cache: false,
	    modal: true,
	    href:ctx + "/web/system/user/add.jsp",
	    onClose:function(){
	    	destroy('dialog','#dialogDiv');
	    },
	    onLoad:function(){
	    	$("#addform").form('load',{});
	    	findDepartByOrganCode(organ[0]);
	    },
	    buttons: [{
            text:'保存',
            iconCls:'icon-ok',
            handler:function(){
            	var bool = $("#addform").form('enableValidation').form('validate');
            	if(!bool){
            		return;
            	}
            	var data = $("#addform").serializeJson();
            	data.organId= organ[0].id;
            	if($.trim($('#addform #departId').combobox('getText')).length!=0){
            		if($.trim($('#addform #departId').combobox('getValue')).length==0){
            			message("部门不存在");
            			return;
            		}
            		data.departId= $('#addform #departId').combobox('getValue');  
            	}
            	$.ajax({
            		type : "POST",
            		url : ctx + "/user/create",
            		data :data,
            		dataType : "json",
            		success : function(data) {
            			if(!showMsg(data,"添加成功")){
            				return;
            			}
            			
            			search(page_);
            			
            			$('#dialog').dialog('close');
            		}
            	});
            }
        },{
            text:'取消',
            iconCls:'icon-cancel',
            handler:function(){
            	$('#dialog').dialog('close');
            }
        }]
	});
}

/**
 * 修改
 */
function edit(){
	var row = null;
	row = getSelectedRow("#datagrid");
	if(!row){
		return;
	}
	$('#dialog').dialog({
	    title: '修改',
	    width: 600,
	    height: 400,
	    closed: false,
	    cache: false,
	    modal: true,
	    href:ctx + "/web/system/user/add.jsp",
	    onClose:function(){
	    	destroy('dialog','#dialogDiv');
	    },
	    onLoad:function(){
	    	$("#addform #dlmm").remove();
	    	$("#addform #qrmm").remove();
	    	$("#addform #mmqd").remove();
	    	$("#addform #username").textbox('readonly');
			$("#addform #id").val(row.id);
			$("#addform").form('load',row);
			var organTree = $.fn.zTree.getZTreeObj("organTree");
			var organ = organTree.getSelectedNodes();
			findDepartByOrganCode(organ[0]);
	    },
	    buttons: [{
	    	text:'保存',
            iconCls:'icon-ok',
            handler:function(){
            	var bool = $("#addform").form('enableValidation').form('validate');
            	if(!bool){
            		return;
            	}
            	var data = $("#addform").serializeJson();
            	if($.trim($('#addform #departId').combobox('getText')).length!=0){
            		if($.trim($('#addform #departId').combobox('getValue')).length==0){
            			message("部门不存在");
            			return;
            		}
            		data.departId= $('#addform #departId').combobox('getValue');  
            	}
            	$.ajax({
            		type : "POST",
            		url : ctx + "/user/update",
            		data :data,
            		dataType : "json",
            		success : function(data) {
            			if(!showMsg(data,"修改成功")){
            				return;
            			}
            			
            			search(page_);
            			
            			$('#dialog').dialog('close');
            		}
            	});
            }
        },{
            text:'取消',
            iconCls:'icon-cancel',
            handler:function(){
            	$('#dialog').dialog('close');
            }
        }]
	});
}

/**
 * 注销
 */
function cancel(){
	var row = null;
	row = getSelectedRow("#datagrid");
	
	if(!row){
		return;
	}
	
	if(row.status == '注销'){
		message("该用户已注销");
		return;
	}
	$.messager.confirm('提示', '确定要注销吗?', function(bool){
	    if (bool){
	    	$.ajax({
	    		type : "POST",
	    		url : ctx + "/user/cancel",
	    		data :{id : row.id},
	    		dataType : "json",
	    		success : function(data) {
	    			if(!showMsg(data,"注销成功")){
        				return;
        			}
	    			
	    			search(page_);
	    			//$('#datagrid').datagrid('reload');
	    		}
	    	});
	    }
	});
}

/**
 * 冻结
 */
function freeze(){
	var row = null;
	row = getSelectedRow("#datagrid");
	
	if(!row){
		return;
	}
	
	if(row.status == '冻结'){
		message("该用户已冻结");
		return;
	}
	$.messager.confirm('提示', '确定要冻结吗?', function(bool){
	    if (bool){
	    	$.ajax({
	    		type : "POST",
	    		url : ctx + "/user/freeze",
	    		data :{id : row.id},
	    		dataType : "json",
	    		success : function(data) {
	    			if(!showMsg(data,"冻结成功")){
        				return;
        			}
	    			
	    			search(page_);
	    			//$('#datagrid').datagrid('reload');
	    		}
	    	});
	    }
	});
}

/**
 * 激活
 */
function active(){
	var row = null;
	row = getSelectedRow("#datagrid");
	
	if(!row){
		return;
	}
	
	if(row.status == '激活'){
		message("该用户已激活");
		return;
	}
	$.messager.confirm('提示', '确定要激活吗?', function(bool){
	    if (bool){
	    	$.ajax({
	    		type : "POST",
	    		url : ctx + "/user/active",
	    		data :{id : row.id},
	    		dataType : "json",
	    		success : function(data) {
	    			if(!showMsg(data,"激活成功")){
        				return;
        			}
	    			
	    			search(page_);
	    		}
	    	});
	    }
	});
}


/**
 * 初始密码
 */
function initPassword(){
	var row = null;
	row = getSelectedRow("#datagrid");
	
	if(!row){
		return;
	}
	
	$.messager.prompt('提示', '确定要修改密码吗?', function(r){
	    if (r){
	    	$.ajax({
	    		type : "POST",
	    		url : ctx + "/user/initPassword",
	    		data :{id : row.id,newPassword:r},
	    		dataType : "json",
	    		success : function(data) {
	    			if(!showMsg(data,"初始化成功")){
        				return;
        			}
	    		}
	    	});
	    }
	});
}

/**
 * 初始密码
 */
function initAllPassword(){
	
	var organTree = $.fn.zTree.getZTreeObj("organTree");
	var organ = organTree.getSelectedNodes();
	
	if(organ.length == 0){
		message("请选择机构");
		return;
	}
	
	var row = null;
	row = getSelectedRow("#datagrid");
	
	if(!row){
		return;
	}

	$.messager.prompt('提示', '确定要修改该机构下所有用户的密码吗?', function(r){
	    if (r){
	    	$.ajax({
	    		type : "POST",
	    		url : ctx + "/user/initAllPassword",
	    		dataType : "json",
	    		data:{organCode:organ[0].code,newPassword:r},
	    		success : function(data) {
	    			if(!showMsg(data,"初始化成功")){
        				return;
        			}
	    		}
	    	});
	    }
	});
}

/**
 * 绑定
 */
function bind(){
	var row = getSelectedRow("#datagrid");
	if(!row){
		return;
	}
	$('#dialog').dialog({
	    title: '绑定',
	    width: 600,
	    height: 400,
	    closed: false,
	    cache: false,
	    modal: true,
	    href:ctx + "/web/system/user/bind.jsp",
	    onClose:function(){
	    	destroy('dialog','#dialogDiv');
	    },
	    onLoad:function(){
/*	    	if("1" == $("#index #organId").val()){
	    		findBindRole(ctx + "/role/findByOrganId",{organId:$("#index #organId").val()});
	    	}else{
	    		findBindRole(ctx + "/role/findByUserId",{userId:$("#index #userId").val()});
	    	}*/
	    	getBindRole(ctx + "/role/findByOrganId",{organId:$("#index #organId").val()});
	    },
	    buttons: [{
            text:'保存',
            iconCls:'icon-ok',
            handler:function(){
            	var data = $("#bindform").serializeJson();
            	var roleIds = new Array();
            	if(data.roleIds instanceof Array){
            		data.roleIds = data.roleIds.join(",");
            	}else{
            		roleIds.push(data.roleIds);
            		data.roleIds = roleIds.join(",");
            	}
            	
            	data.id = row.id;
            	$.ajax({
            		type : "POST",
            		url : ctx + "/user/bind",
            		data :data,
            		dataType : "json",
            		success : function(data) {
            			if(!showMsg(data,"绑定成功")){
            				return;
            			}
            			
            			$('#dialog').dialog('close');
            		}
            	});
            }
        },{
            text:'取消',
            iconCls:'icon-cancel',
            handler:function(){
            	$('#dialog').dialog('close');
            }
        }]
	});
}

/**
 * 通过机构ID或者用户ID获取机构或者用户绑定的角色
 * @param organId 机构ID
 */
function getBindRole(url, data){
	$.ajax({
		type : "GET",
		url : url,
		data :data,
		dataType : "json",
		success : function(data) {
			if(!showMsg(data)){
				return;
			}
			
			if(data.result == 'success'){
				$.each(data.content, function(index,item){
					$("#bindform table").append('<tr><td><input type="checkbox" name=roleIds value=' + item.id + '></input><span>' + item.name + '</span></td></tr>');
				});
				var row = getSelectedRow("#datagrid");
				findRoleById(row.id);
			}
		}
	});
}

/**
 * 通过用户ID获取用户对应的角色
 * @param id 用户ID
 */
function findRoleById(id){
	$.ajax({
		type : "GET",
		url : ctx + "/user/findRoleById",
		data :{id:id},
		dataType : "json",
		success : function(data) {
			if(!showMsg(data)){
				return;
			}
			
			if(data.result == 'success'){
				$.each(data.content, function(index,item){
					$("input[name=roleIds][value='" + item.id +"']").attr('checked','checked');
				});
			}
		}
	});
}

function findDepartByOrganCode(organ){
	$.ajax({
		type : "GET",
		url : ctx + "/depart/query",
		data :{organId:organ.id},
		dataType : "json",
		success : function(data) {
			if(!showMsg(data)){
				return;
			}
			var value = $('#addform #departId').combobox('getValue');
			$('#addform #departId').combobox({
			    valueField:'id',
			    textField:'name',
			    data:data.content,
			    panelHeight:'auto'
			});
			
			if($.trim(value).length != 0){
				$('#addform #departId').combobox('select',value);
			}
		}
	});
}

/**
 * 查询事件
 *//*
$('#datagrid-toolbar #search_link').linkbutton({
	onClick:function(){
		search(page_);
	}
});

*//**
 * 添加事件
 *//*
$('#datagrid-toolbar #add_link').linkbutton({
	onClick:function(){
		add();
	}
});

*//**
 * 修改事件
 *//*
$('#datagrid-toolbar #edit_link').linkbutton({
	onClick:function(){
		edit();
	}
});

*//**
 * 注销事件
 *//*
$('#datagrid-toolbar #cancel_link').linkbutton({
	onClick:function(){
		cancel();
	}
});

*//**
 * 冻结事件
 *//*
$('#datagrid-toolbar #freeze_link').linkbutton({
	onClick:function(){
		freeze();
	}
});

*//**
 * 激活事件
 *//*
$('#datagrid-toolbar #active_link').linkbutton({
	onClick:function(){
		active();
	}
});

*//**
 * 初始化密码
 *//*
$('#datagrid-toolbar #changepassword_link').linkbutton({
	onClick:function(){
		initPassword();
	}
});

*//**
 * 初始化所有用户密码
 *//*
$('#datagrid-toolbar #changeAllPassword_link').linkbutton({
	onClick:function(){
		initAllPassword();
	}
});

*//**
 * 绑定事件
 *//*
$('#datagrid-toolbar #bind_link').linkbutton({
	onClick:function(){
		bind();
	}
});*/